package cn.liyunqi.findimg.demo03;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class JUCExecutorCompletionService {

    static class Task implements Callable<String>{
        private int i;

        public Task(int i){
            this.i = i;
        }

        @Override
        public String call() throws Exception {
            Thread.sleep(1000);
            System.err.println("asdasdasd====" + Thread.currentThread().getName() + "执行完任务：" + i);
            return Thread.currentThread().getName() + "执行完任务：" + i;
        }
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException{
        testExecutorCompletionService();
    }

    private static void testExecutorCompletionService() throws InterruptedException, ExecutionException{
        int numThread = 5;
        ExecutorService executor = Executors.newFixedThreadPool(numThread);
        CompletionService<String> completionService = new ExecutorCompletionService<String>(executor);
        List<Future> futureList = new ArrayList();
        for(int i = 0;i<numThread + 30;i++ ){
            Future<String> future = completionService.submit(new Task(i));
            futureList.add(future);
        }

        new Thread(){
            @Override
            public void run() {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                for (int i = 0; i < futureList.size(); i++) {
                    futureList.get(i).cancel(true);
                }
            }
        }.start();


        for(int i = 0;i<numThread + 20;i++ ){
            try {
                System.out.println("asdasdasd====" + completionService.take().get());
            }catch (Exception ex){
                ex.printStackTrace();
            }

        }


    }
}
